package org.jeecg.modules.data.controller;

import java.time.LocalDate;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.data.entity.TDataReport;
import org.jeecg.modules.data.entity.TInvestigationRelease;
import org.jeecg.modules.data.service.ITInvestigationReleaseService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.service.impl.SysBaseApiImpl;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: t_investigation_release
 * @Author: jeecg-boot
 * @Date:   2025-05-20
 * @Version: V1.0
 */
@Api(tags="t_investigation_release")
@RestController
@RequestMapping("/data/tInvestigationRelease")
@Slf4j
public class TInvestigationReleaseController extends JeecgController<TInvestigationRelease, ITInvestigationReleaseService> {
	@Autowired
	private ITInvestigationReleaseService tInvestigationReleaseService;
	@Resource
	private ISysUserService sysUserService;
	@Resource
	private SysBaseApiImpl sysBaseApi;
	@Resource
	private ISysDictService sysDictService;

	/**
	 * 分页列表查询
	 *
	 * @param tInvestigationRelease
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "t_investigation_release-分页列表查询")
	@ApiOperation(value="t_investigation_release-分页列表查询", notes="t_investigation_release-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<TInvestigationRelease>> queryPageList(TInvestigationRelease tInvestigationRelease,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<TInvestigationRelease> queryWrapper = QueryGenerator.initQueryWrapper(tInvestigationRelease, req.getParameterMap());
		if (tInvestigationRelease.getFlag() != null && tInvestigationRelease.getFlag().equals("3")) {
			queryWrapper.ne("status", "3");
		}
		queryWrapper.orderByDesc("create_time");
		Page<TInvestigationRelease> page = new Page<TInvestigationRelease>(pageNo, pageSize);
		IPage<TInvestigationRelease> pageList = tInvestigationReleaseService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param tInvestigationRelease
	 * @return
	 */
	@AutoLog(value = "t_investigation_release-添加")
	@ApiOperation(value="t_investigation_release-添加", notes="t_investigation_release-添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody TInvestigationRelease tInvestigationRelease) {
		// 校验同作物日期是否交集
		boolean chkFlag = tInvestigationReleaseService.chkDate(tInvestigationRelease);
		if (chkFlag) {
			return Result.error("相同作物调查发布日期存在交集，请修改！");
		}
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		tInvestigationRelease.setCreateBy(user.getUsername());
		tInvestigationRelease.setCreateTime(new Date());
		tInvestigationRelease.setStatus("0");
		tInvestigationReleaseService.save(tInvestigationRelease);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param tInvestigationRelease
	 * @return
	 */
	@AutoLog(value = "t_investigation_release-编辑")
	@ApiOperation(value="t_investigation_release-编辑", notes="t_investigation_release-编辑")
	@PostMapping(value = "/edit")
	public Result<String> edit(@RequestBody TInvestigationRelease tInvestigationRelease) {
		// 校验同作物日期是否交集
		boolean chkFlag = tInvestigationReleaseService.chkDate(tInvestigationRelease);
		if (chkFlag) {
			return Result.error("相同作物调查发布日期存在交集，请修改！");
		}
		int chkTotal = tInvestigationReleaseService.chkReport(tInvestigationRelease.getId());
		if (chkTotal > 0) {
			return Result.error("该调查发布已填报，不允许修改！");
		}
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		tInvestigationRelease.setUpdateBy(user.getUsername());
		tInvestigationRelease.setUpdateTime(new Date());
		tInvestigationReleaseService.updateById(tInvestigationRelease);

		String text = sysDictService.queryDictTextByKey("crop_type", tInvestigationRelease.getCropType());
		String title = text + "【"+ DateUtils.formatDate(tInvestigationRelease.getStartTime()) + "_" + DateUtils.formatDate(tInvestigationRelease.getEndTime()) +"】";
		List<String> userList = sysUserService.getUserByRoleCode();
		// 异步发送消息
		CompletableFuture.runAsync(() -> {
			for (String username : userList) {
				MessageDTO messageDTO = new MessageDTO();
				messageDTO.setFromUser(user.getUsername());
				messageDTO.setToUser(username);
				messageDTO.setTitle("待办事项");
				messageDTO.setContent(title + "修改成功，变更内容已下发！");
				sysBaseApi.sendSysAnnouncement(messageDTO);
			}
		});
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param release
	 * @return
	 */
	@AutoLog(value = "t_investigation_release-通过id删除")
	@ApiOperation(value="t_investigation_release-通过id删除", notes="t_investigation_release-通过id删除")
	@PostMapping(value = "/delete")
	public Result<String> delete(@RequestBody TInvestigationRelease release) {
		TInvestigationRelease ti = tInvestigationReleaseService.getById(release.getId());
		String text = sysDictService.queryDictTextByKey("crop_type", ti.getCropType());
		String title = text + "【"+ DateUtils.formatDate(ti.getStartTime()) + "_" + DateUtils.formatDate(ti.getEndTime()) +"】";
		int chkTotal = tInvestigationReleaseService.chkReport(release.getId());
		if (chkTotal > 0) {
			return Result.error("该调查发布已填报，不允许删除！");
		}
		tInvestigationReleaseService.removeById(release.getId());
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		List<String> userList = sysUserService.getUserByRoleCode();

		// 异步发送消息
		CompletableFuture.runAsync(() -> {
			for (String username : userList) {
				MessageDTO messageDTO = new MessageDTO();
				messageDTO.setFromUser(user.getUsername());
				messageDTO.setToUser(username);
				messageDTO.setTitle("待办事项");
				messageDTO.setContent(title + "删除成功，取消填报信息已下发！");
				sysBaseApi.sendSysAnnouncement(messageDTO);
			}
		});
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param tInvestigationRelease
	 * @return
	 */
	@AutoLog(value = "t_investigation_release-批量删除")
	@ApiOperation(value="t_investigation_release-批量删除", notes="t_investigation_release-批量删除")
	@PostMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestBody TInvestigationRelease tInvestigationRelease) {
		String ids = tInvestigationRelease.getId();
		for (String id : ids.split(",")) {
			int chkTotal = tInvestigationReleaseService.chkReport(id);
			if (chkTotal > 0) {
				return Result.error("该调查发布已填报，不允许删除！");
			}
		}
		this.tInvestigationReleaseService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "t_investigation_release-通过id查询")
	@ApiOperation(value="t_investigation_release-通过id查询", notes="t_investigation_release-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<TInvestigationRelease> queryById(@RequestParam(name="id",required=true) String id) {
		TInvestigationRelease tInvestigationRelease = tInvestigationReleaseService.getById(id);
		if(tInvestigationRelease==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(tInvestigationRelease);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param tInvestigationRelease
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, TInvestigationRelease tInvestigationRelease) {
        return super.exportXls(request, tInvestigationRelease, TInvestigationRelease.class, "t_investigation_release");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, TInvestigationRelease.class);
    }


	 /**
	  * 调查发布-分页列表选择
	  *
	  * @param tInvestigationRelease
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @ApiOperation(value="调查发布-分页列表选择", notes="调查发布-分页列表选择")
	 @GetMapping(value = "/reportInList")
	 public Result<IPage<TInvestigationRelease>> queryPageReportInList(TInvestigationRelease tInvestigationRelease,
															   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
															   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
															   HttpServletRequest req) {
		 QueryWrapper<TInvestigationRelease> queryWrapper = QueryGenerator.initQueryWrapper(tInvestigationRelease, req.getParameterMap());
		 queryWrapper.le("start_time", LocalDate.now());
		 queryWrapper.ge("end_time", LocalDate.now());
		 queryWrapper.eq("status", "1");
		 queryWrapper.orderByDesc("create_time");
		 Page<TInvestigationRelease> page = new Page<TInvestigationRelease>(pageNo, pageSize);
		 IPage<TInvestigationRelease> pageList = tInvestigationReleaseService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	 /**
	  *  修改状态
	  *
	  * @param release
	  * @return
	  */
	 @AutoLog(value = "t_data_report-修改状态")
	 @ApiOperation(value="t_data_report-修改状态", notes="t_data_report-修改状态")
	 @PostMapping(value = "/editStatus")
	 public Result<String> editStatus(@RequestBody TInvestigationRelease release) {
		 TInvestigationRelease ti = tInvestigationReleaseService.getById(release.getId());
		 String text = sysDictService.queryDictTextByKey("crop_type", ti.getCropType());
		 String title = text + "【"+ DateUtils.formatDate(ti.getStartTime()) + "_" + DateUtils.formatDate(ti.getEndTime()) +"】";
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 tInvestigationReleaseService.updateStatus(release);
		 List<String> userList = sysUserService.getUserByRoleCode();
		 CompletableFuture.runAsync(() -> {
			 for (String username : userList) {
				 MessageDTO messageDTO = new MessageDTO();
				 messageDTO.setFromUser(user.getUsername());
				 messageDTO.setToUser(username);
				 messageDTO.setTitle("待办事项");
				 messageDTO.setContent(title + "发布成功，新填报消息已下发！");
				 sysBaseApi.sendSysAnnouncement(messageDTO);
			 }
		 });
		 return Result.OK("发布成功，新填报消息已下发各市、县用户！");
	 }

	 /**
	  *  修改作废状态
	  *
	  * @param release
	  * @return
	  */
	 @AutoLog(value = "t_data_report-修改作废状态")
	 @ApiOperation(value="t_data_report-修改作废状态", notes="t_data_report-修改作废状态")
	 @PostMapping(value = "/editZFStatus")
	 public Result<String> editZFStatus(@RequestBody TInvestigationRelease release) {
		 TInvestigationRelease ti = tInvestigationReleaseService.getById(release.getId());
		 String text = sysDictService.queryDictTextByKey("crop_type", ti.getCropType());
		 String title = text + "【"+ DateUtils.formatDate(ti.getStartTime()) + "_" + DateUtils.formatDate(ti.getEndTime()) +"】";
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 int chkTotal = tInvestigationReleaseService.chkReport(release.getId());
		 if (chkTotal > 0) {
			 tInvestigationReleaseService.updateStatus(release);
			 List<String> userList = sysUserService.getUserByRoleCode();
			 CompletableFuture.runAsync(() -> {
				 for (String username : userList) {
					 MessageDTO messageDTO = new MessageDTO();
					 messageDTO.setFromUser(user.getUsername());
					 messageDTO.setToUser(username);
					 messageDTO.setTitle("待办事项");
					 messageDTO.setContent(title + "作废成功，取消填报消息已下发！");
					 sysBaseApi.sendSysAnnouncement(messageDTO);
				 }
			 });
			 return Result.OK("作废成功，取消填报消息已下发各市、县用户！");
		 } else {
			 return Result.error("已发布未填报，作废失败！");
		 }
	 }
}
